package com.v1.video.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.MaiPaigeLoadinImage;
import com.v1.video.engine.NetEngine;
import com.v1.video.engine.RequestEngine;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.util.Helper;
import com.v1.video.util.Utility;

import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * 启动界面
 */
public class SplashActivity extends BaseActivity {

	private static final String TAG = "SplashActivity";
	private static final long LOADING_TIME = 3000;

	private SharedPreferences sp;

	private LinearLayout mLaySplash;
	private ImageView loadingIv;
	private long startTime;
	private boolean animFinish = false;
	private MaiPaigeLoadinImage mLoadinImage;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MobclickAgent.onEvent(this, "Loading");
		setContentView(R.layout.activity_splash);
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("loading页");
		MobclickAgent.onResume(this);
		JPushInterface.onResume(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("loading页");
		MobclickAgent.onPause(this);
		JPushInterface.onPause(this);
		animFinish = false;
	}

	@Override
	protected void initView() {
		mLaySplash = (LinearLayout) findViewById(R.id.rlSplash);
		loadingIv = (ImageView) findViewById(R.id.iv_loading);
	}

	@Override
	protected void setListener() {

	}

	@Override
	protected void initData() {
		sp = getSharedPreferences(Constant.APP_INFO, MODE_PRIVATE);
		AlphaAnimation aa = new AlphaAnimation(1.0f, 1.0f);
		aa.setDuration(3000);
		aa.setAnimationListener(new AnimationListener() {
			public void onAnimationStart(Animation animation) {

			}

			public void onAnimationRepeat(Animation animation) {

			}

			public void onAnimationEnd(Animation animation) {
				localSpread();
			}
		});
		mLaySplash.startAnimation(aa);
		// startTime = System.currentTimeMillis();
		new NetEngine().startingUpToServer(this);
		loadCachedData();
	}

	private void localSpread() {

		try {
			if (mLoadinImage != null
					&& !TextUtils.isEmpty(mLoadinImage.getType())
					&& "I".equals(mLoadinImage.getType())) {
				Bitmap decodeFile = BitmapFactory.decodeFile(sp.getString(
						"loading_page_path", ""));
				if (decodeFile != null) {
					final AlphaAnimation bb = new AlphaAnimation(1.0f, 1.0f);
					bb.setDuration(3000);
					bb.setAnimationListener(new AnimationListener() {
						public void onAnimationStart(Animation animation) {

						}

						public void onAnimationRepeat(Animation animation) {

						}

						public void onAnimationEnd(Animation animation) {
							animFinish = true;
							loginHomeUI();
						}
					});
//					ImageLoader.getInstance().displayImage("http://img.app.v1.cn/image/ads/day_20170215/201702151738157423.jpg",
//							loadingIv,
//							Constant.VIDEO_10_16_OPTION_ROUNDED);
					loadingIv.setImageBitmap(decodeFile);
					mLaySplash.startAnimation(bb);
					if ("0".equals(mLoadinImage.getPid())) {
						RequestEngine request = new RequestEngine();
						request.sendADVLogToServer(SplashActivity.this, ""
								+ Constant.STATE_ADV_CZBM_2, ""
								+ Constant.STATE_ADV_CZSX_1, ""
								+ Constant.STATE_ADV_CZJG_1);
						new NetEngine().AdUpToServer(SplashActivity.this,
								mLoadinImage.getPid(), LoginInfo.getInstance()
										.getUserId(), "10", "1", "-1");
						if (!TextUtils.isEmpty(mLoadinImage.getUrl())) {
							loadingIv.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									RequestEngine request = new RequestEngine();
									request.sendADVLogToServer(
											SplashActivity.this,
											"" + Constant.STATE_ADV_CZBM_1,
											"" + Constant.STATE_ADV_CZSX_1, ""
													+ Constant.STATE_ADV_CZJG_3);
									new NetEngine().AdUpToServer(
											SplashActivity.this, mLoadinImage
													.getPid(), LoginInfo
													.getInstance().getUserId(),
											"10", "2", "-1");
									String url = mLoadinImage.getUrl();
									if(!url.contains("http://")){
										url= "http://"+mLoadinImage.getUrl();
									}
									Uri uri = Uri.parse(url);
									Intent it = new Intent(Intent.ACTION_VIEW, uri);
									SplashActivity.this.startActivity(it);
									
//									startActivityHelper(new Intent(
//											SplashActivity.this,
//											WebViewActivity3.class)
//											.putExtra("adLink",
//													mLoadinImage.getUrl())
//											.putExtra(
//													"type",
//													WebViewActivity3.STATE_TYPE_1));
								}
							});
						}
					} else {
						requestExposure(mLoadinImage.getPm());
						new NetEngine().AdUpToServer(SplashActivity.this,
								mLoadinImage.getPid(), LoginInfo.getInstance()
										.getUserId(), "10", "1", "-1");
						if ("I".equals(mLoadinImage.getType())
								&& !TextUtils.isEmpty(mLoadinImage.getUrl())) {
							loadingIv.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									requestClickCheck(mLoadinImage.getCm());
									new NetEngine().AdUpToServer(
											SplashActivity.this, mLoadinImage
													.getPid(), LoginInfo
													.getInstance().getUserId(),
											"10", "2", "-1");
									String url = mLoadinImage.getUrl();
									if(!url.contains("http://")){
										url= "http://"+mLoadinImage.getUrl();
									}
									Uri uri = Uri.parse(url);
									Intent it = new Intent(Intent.ACTION_VIEW, uri);
									SplashActivity.this.startActivity(it);
//									startActivityHelper(new Intent(
//											SplashActivity.this,
//											WebViewActivity3.class)
//											.putExtra("adLink",
//													mLoadinImage.getUrl())
//											.putExtra(
//													"type",
//													WebViewActivity3.STATE_TYPE_1));
								}
							});
						}
					}
				} else {
					animFinish = true;
					loginHomeUI();
				}
			} else {
				animFinish = true;
				loginHomeUI();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 请求曝光
	 * 
	 * @param pm
	 */
	private void requestExposure(List<String> pm) {
		if (pm != null && pm.size() > 0) {
			for (int i = 0; i < pm.size(); i++) {
				String pmStr = pm.get(i);
				if (!TextUtils.isEmpty(pmStr)) {
					RequestManager.getInstance().getRequest(
							SplashActivity.this, pmStr);
				}
			}
		}
	}

	/**
	 * 请求点击监测
	 * 
	 * @param cm
	 */
	private void requestClickCheck(List<String> cm) {
		if (cm != null && cm.size() > 0) {
			for (int i = 0; i < cm.size(); i++) {
				String pmStr = cm.get(i);
				if (!TextUtils.isEmpty(pmStr)) {
					RequestManager.getInstance().getRequest(
							SplashActivity.this, pmStr);
				}
			}
		}
	}

	private void startActivityHelper(Intent intent) {
		if (Helper.checkConnection(SplashActivity.this)) {
			SplashActivity.this.startActivity(intent);
		}
	}

	private void loginHomeUI() {
		if (animFinish) {
			// long endTime = System.currentTimeMillis();
			// if (endTime - startTime < LOADING_TIME) {
			// SystemClock.sleep(LOADING_TIME - (endTime - startTime));
			// }
			Intent intent = null;
//			if (sp.getBoolean("first_start", true)) {
//				intent = new Intent(this, GuideActivity.class);
//			} else {
//				intent = new Intent(this, TestActivity.class);
				intent = new Intent(this, MainPageNewActivity.class);
//			}
			startActivity(intent);
			finish();
		}
	}

	/**;
	 * 加载本地缓存数据
	 */
	private void loadCachedData() {
		String json = Utility.ReadTxtFile(this, "AdvCache.txt");
		if (!TextUtils.isEmpty(json)) {
			Gson gson = new Gson();
			mLoadinImage = gson.fromJson(json, MaiPaigeLoadinImage.class);
		}
	}
}
